import axios from 'axios'
import { Toast, Dialog } from 'vant'
import store from '@/store'

// 全局控制：等待 token 就绪再发送需要鉴权的请求
let tokenReadyResolve = null
let tokenReadyPromise = new Promise((resolve) => {
  tokenReadyResolve = resolve
})

// 如果启动时已有 token，直接标记就绪
const initialToken = (store && store.state && store.state.user && store.state.user.token) || localStorage.getItem('token')
if (initialToken && typeof tokenReadyResolve === 'function') {
  tokenReadyResolve()
  tokenReadyResolve = null
}

export function markTokenReady() {
  if (typeof tokenReadyResolve === 'function') {
    tokenReadyResolve()
    tokenReadyResolve = null
  }
}

// 提供等待就绪的方法，供路由守卫等位置统一等待
export function waitTokenReady() {
  return tokenReadyPromise
}

// 创建axios实例
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const request = axios.create({
  // 开发环境使用代理，生产环境使用完整URL
  baseURL: process.env.NODE_ENV === 'development'
    ? '/api' // 开发环境使用代理路径
    : (process.env.VUE_APP_BASE_API || 'http://localhost:3000/api'), // 生产环境使用完整URL
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
request.interceptors.request.use(
  async config => {
    // 显示加载提示
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    })

    // 按需添加 token 到请求头：当 headers.isToken === false 时不添加
    const shouldAttachToken = !(config.headers && config.headers.isToken === false)
    if (config.headers && Object.prototype.hasOwnProperty.call(config.headers, 'isToken')) {
      // 不把控制字段传给后端
      delete config.headers.isToken
    }
    if (shouldAttachToken) {
      let token = store.state.user.token || localStorage.getItem('token')
      if (!token) {
        // 等待 token 就绪
        await tokenReadyPromise
        token = store.state.user.token || localStorage.getItem('token')
      }
      if (token) {
        if (!config.headers) config.headers = {}
        config.headers['X-Access-Token'] = `${token}`
      }
    }

    // 添加时间戳，防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }

    return config
  },
  error => {
    Toast.clear()
    const message = '请求发送失败'
    Toast.fail(message)
    console.log(error);
    // 统一不抛错，返回统一结构
    return Promise.resolve({ success: false, message, error })
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    Toast.clear()

    const { data, status } = response
    console.log(response, '00000000000000000');
    // 处理不同的HTTP状态码
    if (status === 200) {
      // 成功状态码下，按业务码判断
      if (data && (data.errorCode === '000000' || data.success === true)) {
        return data
      }
      if (data && (data.errorCode === '401' || data.errorCode === '403')) {
        handleUnauthorized()
        const message = data.message || '认证失败'
        Toast.fail(message)
        return { success: false, message, code: '401', data }
      }
      const message = (data && data.message) || '请求失败'
      Toast.fail(message)
      return { success: false, message, code: (data && (data.errorCode || data.code)) || status, data }
    }

    // 非 200，按失败返回
    return { success: false, message: '请求失败', code: status, data }
  },
  error => {
    Toast.clear()

    const { response } = error
    let message = '请求失败'
    let code = 'NETWORK_ERROR'

    if (response) {
      console.log(response, '9999999999');

      const { status, data } = response
      code = status
      switch (status) {
        case 400:
          message = (data && data.message) || '请求参数错误'
          break
        case 401:
          handleUnauthorized()
          message = '认证失败'
          break
        case 403:
          message = '没有权限访问'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = (data && data.message) || '请求失败'
      }
    } else if (error.code === 'ECONNABORTED') {
      message = '请求超时，请稍后重试'
      code = 'TIMEOUT'
    } else {
      message = '网络错误，请检查网络连接'
    }

    Toast.fail(message)
    // 统一不抛错，返回统一结构
    return Promise.resolve({ success: false, message, code, error })
  }
)

// 处理未授权情况
function handleUnauthorized() {
  Dialog.confirm({
    title: '提示',
    message: '登录已过期，请重新登录',
    confirmButtonText: '重新登录',
    showCancelButton: false
  }).then(() => {
    // 清除本地存储的用户信息
    // localStorage.removeItem('token')
    // localStorage.removeItem('userInfo')
    // store.dispatch('user/logout')
    // console.log('在这里跳转到指定页面');
    // window.location.reload()

    // 跳转到登录页
    // router.replace('/login')
  })
}

export default request 